﻿using ELF.Gateway.Jwt;
using Microsoft.IdentityModel.Tokens;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace Microsoft.Extensions.DependencyInjection;

public static class DependencyInjection
{
    public static void AddOpenIddictAuth(this IHostApplicationBuilder builder)
    {
        // Customise default API behaviour
        ConfigureOpenIddict(builder.Services, builder.Configuration);

        //builder.Services.AddSingleton<GatewayJwtService>();
        builder.Services.AddAuthentication("OpenIddict.Validation.AspNetCore");
    }

    public static void ConfigureOpenIddict(IServiceCollection services, IConfiguration configuration)
    {
        var encryptionKeyText = configuration["OpenIddict:EncryptionKey"];
        if (string.IsNullOrEmpty(encryptionKeyText))
        {
            throw new ArgumentNullException("OpenIddict:EncryptionKey", "请配置证书密钥！");
        }

        var identity_server_address = configuration["OpenIddict:Issuer"];
        if (string.IsNullOrEmpty(identity_server_address))
        {
            throw new ArgumentNullException("OpenIddict:Issuer", "请配置身份服务器地址！");
        }

        //// 配置OpenIddict
        //services.AddOpenIddict()
        //    .AddValidation(builder =>
        //    {
        //        builder.SetIssuer(identity_server_address);
        //        var encryptionKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(encryptionKeyText));
        //        builder.AddEncryptionKey(encryptionKey);
        //        builder.UseSystemNetHttp();
        //        builder.UseAspNetCore();
        //    });

        // 添加身份验证
        services.AddAuthentication("OpenIddict.Validation.AspNetCore")
            .AddJwtBearer(options =>
            {
                options.Authority = configuration["OpenIddict:Issuer"];
                //options.Audience = "resource_server"; // 与你的 OpenIddict 服务器配置一致
                options.RequireHttpsMetadata = false; // 生产环境应为 true

                // 如果你需要保留加密密钥验证
                if (!string.IsNullOrEmpty(configuration["OpenIddict:EncryptionKey"]))
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,          // 验证签发者
                        ValidIssuer = configuration["OpenIddict:Issuer"], // 明确指定合法签发者

                        ValidateAudience = false,       // 你服务器配置中没有明确设置Audience
                        ValidateLifetime = true,        // 验证有效期

                        // 加密密钥必须与服务器一致
                        TokenDecryptionKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(encryptionKeyText)),

                        // 签名验证设置（你服务器使用了开发签名证书）
                        ValidateIssuerSigningKey = false,
                        //IssuerSigningKey = new X509SecurityKey(new X500DistinguishedName("CN=OpenIddict Server Signing Certificate"))
                        //IssuerSigningKey = new X509SecurityKey(new X509Certificate2("开发证书路径"))
                        // 如果没有证书文件，可以暂时注释这行，使用下面的时钟偏差设置
                    };
                }
            });

        services.AddAuthentication(options =>
        {
            options.DefaultScheme = "OpenIddict.Validation.AspNetCore";
            options.DefaultChallengeScheme = "OpenIddict.Validation.AspNetCore";
        });
    }
}
